package org.geometerplus.android.fbreader;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

//import net.youmi.android.AdManager;//
//import net.youmi.android.AdView;
//import net.youmi.android.appoffers.YoumiOffersManager;

import org.geometerplus.android.fbreader.api.PluginApi;
import org.geometerplus.android.fbreader.library.BookInfoActivity;
import org.geometerplus.android.fbreader.library.LibraryActivity;
import org.geometerplus.android.fbreader.library.SQLiteBooksDatabase;
import org.geometerplus.android.fbreader.network.NetworkLibraryActivity;
import org.geometerplus.android.fbreader.preferences.PreferenceActivity;
import org.geometerplus.android.util.BookUtil;
import org.geometerplus.android.util.Constant;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.library.Book;
import org.geometerplus.fbreader.library.BooksCursorAdapter;
import org.geometerplus.fbreader.library.Library;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.zixuanstudio.ebook.R;
import org.geometerplus.zlibrary.ui.android.application.ZLAndroidApplicationWindow;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;
import org.geometerplus.zlibrary.ui.android.view.ShelvesView;

import com.waps.AppConnect;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

/**
 * 
 * @author fan
 * 
 */
public class BookShelf extends Activity implements OnClickListener {

	private static final String TAG = "BookShelf";

	private static final int DIALOG_CONFIRM = 0;
	private static final int DIALOG_OPTION = 1;
	private static final int DIALOG_CONFIRM_DELETE = 5;
	private static final int DIALOG_CLEAR = 6;
	private static final int DIALOG_NOTIFICATION = 12;

	private static final int OPTION_OPEN = 0;
	private static final int OPTION_DETAIL = 1;
	private static final int OPTION_REFRESH = 2;
	private static final int OPTION_DELETE = 3;

	private static final int REQUEST_VIEW_BOOK = 10;
	// add by wenyd on 2011-12-21
	private TextView titleTextView;
	private Button rightButton;
	private ImageButton goNetStoreButton;
	private ShelvesView mShelevesView;
	private BooksCursorAdapter mCursorAdapter;

	private long mBookId = -1;
	private Cursor mCursor = null;

	private BookOptionListener mOptionListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Thread.setDefaultUncaughtExceptionHandler(new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(
				this));

		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.screen_shelves);
		if (SQLiteBooksDatabase.Instance() == null) {
			new SQLiteBooksDatabase(this, "READER");
		}

		/*
		 * AdView adView = new AdView(this); FrameLayout.LayoutParams params =
		 * new FrameLayout.LayoutParams( FrameLayout.LayoutParams.FILL_PARENT,
		 * FrameLayout.LayoutParams.WRAP_CONTENT); // 设置广告出现的位置(悬浮于屏幕右下角)
		 * params.gravity = Gravity.BOTTOM | Gravity.RIGHT; // 将广告视图加入Activity中
		 * // addContentView(adView, params);
		 */
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Log.v("BookShelf", "onNewIntent:");
	}

	private void init() {
		// ----add by wenyd on 2011-12-21---start-
		// rightButton = (Button) findViewById(R.id.rightButton);
		titleTextView = (TextView) findViewById(R.id.title);
		// goNetStoreButton = (ImageButton) findViewById(R.id.goNetStore);
		// rightButton.setVisibility(View.GONE);
		titleTextView.setText(R.string.reader);
		// ----add by wenyd on 2011-12-21---end-

		mCursor = Book.getAllBook();
		mShelevesView = (ShelvesView) findViewById(R.id.grid_shelves);
		mShelevesView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long id) {
				mBookId = id;
				RLog.v("BookShelf", "onItemLongClick:" + mBookId);
				mOptionListener = new BookOptionListener();
				showDialog(DIALOG_OPTION);
				return true;
			}

		});
		// mAdapter = new BooksAdapter(this, mShelevesView);
		mCursorAdapter = new BooksCursorAdapter(this, mCursor);
		// mCursorAdapter.registerDataSetObserver(mObserver);
		mShelevesView.setAdapter(mCursorAdapter);
		mShelevesView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				String bookPath = null;
				try {
					bookPath = Book.getById(id).File.getPath();

				} catch (Exception e) {
					e.printStackTrace();
				}

				if (bookPath != null) {
					boolean isExist = isExistOnSdcard(bookPath);
					Intent intent = new Intent(getApplicationContext(),
							FBReader.class);
					intent.setAction(Intent.ACTION_VIEW);
					intent.putExtra(FBReader.BOOK_PATH_KEY,
							Book.getById(id).File.getPath());
					startActivity(intent);
				} else {
					Toast.makeText(BookShelf.this, R.string.no_exist_on_sdcard,
							Toast.LENGTH_SHORT).show();
					Book.deleteBookById(id);
					mCursorAdapter.notifyDataSetChanged();
				}
			}

		});

		if (((ZLAndroidApplication) getApplication()).myMainWindow == null) {
			RLog.v("ZLAndroidActivity", "@@myWindow==null");
			FBReaderApp application = new FBReaderApp(null);

			((ZLAndroidApplication) getApplication()).myMainWindow = new ZLAndroidApplicationWindow(
					application);
		}
	}

	public boolean isExistOnSdcard(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	protected void onDestroy() {

		if (mCursor != null)
			mCursor.close();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
		super.onDestroy();
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		System.gc();
		System.gc();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// mCursorAdapter.unregisterDataSetObserver(mObserver);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		init();
	}

	@Override
	protected void onStart() {
		super.onStart();
		SharedPreferences preference = getSharedPreferences(
				Constant.REAER_PREFERENCE_NAME, this.MODE_PRIVATE);
		boolean firstLaunch = preference
				.getBoolean(Constant.FIRST_LAUNCH, true);
		if (firstLaunch) {
			showDialog(DIALOG_NOTIFICATION);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		AppConnect.getInstance(this).getPushAd();
		menu.clear();
		String name = ZLResource.resource("menu")
				.getResource(ActionCode.SHOW_LIBRARY).getValue();
		menu.add(0, R.drawable.ic_menu_library, 0, name).setIcon(
				R.drawable.ic_menu_library);
		menu.add(
				0,
				R.drawable.ic_menu_networklibrary,
				0,
				ZLResource.resource("menu")
						.getResource(ActionCode.SHOW_NETWORK_LIBRARY)
						.getValue()).setIcon(R.drawable.ic_menu_networklibrary);

		menu.add(
				0,
				R.drawable.default_cover,
				0,
				ZLResource.resource("menu")
						.getResource(ActionCode.SHOW_PREFERENCES).getValue())
				.setIcon(R.drawable.ic_menu_day);
		menu.add(0, R.drawable.ic_menu_toc, 0, R.string.quit).setIcon(
				R.drawable.ic_menu_toc);
		menu.add(0, R.drawable.ic_menu_thumbnail, 0, R.string.youni_offer)
				.setIcon(R.drawable.ic_menu_add);
		if (mCursor != null) {
			if (mCursor.getCount() != 0) {
				menu.add(0, R.drawable.ic_menu_languages, 0,
						R.string.delete_all_book).setIcon(
						R.drawable.ic_menu_languages);
			}
		}

		menu.add(0, R.drawable.ic_menu_refresh, 0, R.string.refresh_bookshelf)
				.setIcon(R.drawable.ic_menu_refresh);
		menu.add(0, R.drawable.ic_tab_most_visited_unselected, 0,
				R.string.app_about).setIcon(
				R.drawable.ic_tab_most_visited_unselected);
		return super.onPrepareOptionsMenu(menu);
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { String name =
	 * ZLResource.resource("menu")
	 * .getResource(ActionCode.SHOW_LIBRARY).getValue(); menu.add(0,
	 * R.drawable.ic_menu_library, 0, name).setIcon(
	 * R.drawable.ic_menu_library); menu.add( 0,
	 * R.drawable.ic_menu_networklibrary, 0, ZLResource.resource("menu")
	 * .getResource(ActionCode.SHOW_NETWORK_LIBRARY)
	 * .getValue()).setIcon(R.drawable.ic_menu_networklibrary); menu.add( 0,
	 * R.drawable.cover_ebk, 0, ZLResource.resource("menu")
	 * .getResource(ActionCode.SHOW_PREFERENCES).getValue())
	 * .setIcon(R.drawable.ic_menu_day); menu.add(0, R.drawable.ic_menu_delete,
	 * 0, R.string.delete_all_book) .setIcon(R.drawable.ic_menu_delete);
	 * menu.add(0,R.drawable.base_default,0,R.string.quit); return true; }
	 */

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		RLog.v("BookShelf", "onOptionItemSelected:" + item.getItemId());
		Intent intent = null;
		switch (item.getItemId()) {
		case R.drawable.ic_menu_library:
			intent = new Intent(this, LibraryActivity.class);
			startActivity(intent);
			break;
		case R.drawable.ic_menu_networklibrary:
			intent = new Intent(this, NetworkLibraryActivity.class);
			intent.putExtra("SingleCatalog", true);
			startActivity(intent);
			break;
		case R.drawable.ic_menu_refresh:
			refreshBooksList();
			break;
		case R.drawable.default_cover:
			intent = new Intent(this, PreferenceActivity.class);
			startActivityForResult(intent, FBReader.REPAINT_CODE);
			break;
		case R.drawable.ic_menu_languages:
			showDialog(DIALOG_CLEAR);
			break;
		case R.drawable.ic_menu_toc:
			showDialog(DIALOG_CONFIRM);
			break;
		case R.drawable.ic_tab_most_visited_unselected:
			Intent aboutIntent = new Intent(BookShelf.this, ZXReaderAbout.class);
			startActivity(aboutIntent);
			break;
		case R.drawable.ic_menu_thumbnail:
			AppConnect.getInstance(this).showOffers(this);
			break;
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_NOTIFICATION:
			return new AlertDialog.Builder(BookShelf.this)
					.setOnCancelListener(new OnCancelListener() {

						public void onCancel(DialogInterface dialog) {
							SharedPreferences preference = getSharedPreferences(
									Constant.REAER_PREFERENCE_NAME,
									BookShelf.this.MODE_PRIVATE);
							SharedPreferences.Editor editor = preference.edit();
							editor.putBoolean(Constant.FIRST_LAUNCH, false);
							editor.commit();
						}

					}).setTitle(R.string.new_version_tip)
					.setMessage(R.string.new_version).create();
		case DIALOG_CONFIRM:
			return new AlertDialog.Builder(BookShelf.this)
					.setTitle(R.string.quit)
					.setMessage(R.string.confirm_quit)
					.setPositiveButton(R.string.dialog_ok,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									finish();
									//
									android.os.Process
											.killProcess(android.os.Process
													.myPid());
									System.exit(0);
								}
							})
					.setNegativeButton(R.string.dialog_cancel,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).create();
		case DIALOG_OPTION:
			return new AlertDialog.Builder(BookShelf.this).setItems(
					R.array.dialog_option, mOptionListener).create();
		case DIALOG_CLEAR:
			return new AlertDialog.Builder(BookShelf.this)
					.setMessage(getString(R.string.delete_all_book))
					.setTitle(R.string.epub_reader)
					.setPositiveButton(R.string.dialog_ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Book.deleteAllBook();
									refreshBooksList();
								}
							})
					.setNegativeButton(R.string.dialog_cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).create();
		case DIALOG_CONFIRM_DELETE:
			View v = LayoutInflater.from(this).inflate(
					R.layout.delete_book_dialog, null);
			final CheckBox delete = (CheckBox) v.findViewById(R.id.is_delete);
			final Button okBtn = (Button) v.findViewById(R.id.delete_book);
			final Button cancelBtn = (Button) v.findViewById(R.id.cancel);
			okBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String bookPath = Book.getBookPathById(mBookId);
					if (delete.isChecked()) {
						File file = new File(bookPath);

						try {
							if (file != null && file.exists()) {
								file.delete();
							}
						} catch (Exception e) {
						}
					}
					Book.deleteBookById(mBookId);
					refreshBooksList();
					dismissDialog(DIALOG_CONFIRM_DELETE);
				}

			});
			cancelBtn.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
				}

			});
			return new AlertDialog.Builder(BookShelf.this).setView(v).create();
		}
		return null;
	}

	private class DeleteBookDialog extends AlertDialog {
		private long id = -1;

		protected DeleteBookDialog(Context context, long bookId) {
			super(context);
			id = bookId;
		}

	}

	@Override
	public void onBackPressed() {
		showDialog(DIALOG_CONFIRM);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.goNetStore:
			// Read
			startActivity(new Intent(getApplicationContext(),
					NetworkLibraryActivity.class));
			break;

		default:
			break;
		}
	}

	private class CancelListener implements DialogInterface.OnCancelListener {

		@Override
		public void onCancel(DialogInterface dialog) {
			dialog.dismiss();
		}

	}

	private void refreshBooksList() {
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
			mCursor = Book.getAllBook();
			mCursorAdapter = new BooksCursorAdapter(this, mCursor);
			mShelevesView.setAdapter(mCursorAdapter);
			// mCursorAdapter.notifyDataSetChanged();
		}
	}

	private class BookOptionListener implements DialogInterface.OnClickListener {

		private long bookId = -1;
		private Book book = null;

		public BookOptionListener() {
			// bookId = id;
			RLog.v("BookOptionLIistener", "bookId:" + bookId);
		}

		public void setBookId(long id) {
			RLog.v("BookOptionListener", "setBookId:" + id);
			bookId = id;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			String path = null;
			switch (which) {
			case OPTION_OPEN:
				path = Book.getBookPathById(mBookId);
				if (path != null)
					startActivity(new Intent(getApplicationContext(),
							FBReader.class).setAction(Intent.ACTION_VIEW)
							.putExtra(FBReader.BOOK_PATH_KEY, path)
							.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				break;
			case OPTION_DETAIL:
				path = Book.getBookPathById(mBookId);
				startActivity(new Intent(BookShelf.this, BookInfoActivity.class)
						.putExtra(BookInfoActivity.CURRENT_BOOK_PATH_KEY, path));
				break;
			case OPTION_REFRESH:
				path = Book.getBookPathById(mBookId);
				ZLFile file = ZLFile.createFileByPath(path);
				Book.updateBookCoverByPath(file);
				break;
			case OPTION_DELETE:
				showDialog(DIALOG_CONFIRM_DELETE);
				break;
			}
		}

	}

}
